package com.wlz.bio;

import lombok.extern.slf4j.Slf4j;

import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author wlz
 * @date 2022-07-06  8:39 下午
 */
@Slf4j
public class SocketServer {

    public static void main(String[] args) throws Exception{

        ServerSocket serverSocket = new ServerSocket(9000);

        while (true) {
            log.info(" 等待连接 。。。。");
            Socket socket = serverSocket.accept(); // 如果有两个客户端，另一个客户端会阻塞在这里，直到前一个客户端执行完成
            log.info("有客户端连接进来.....");
//            handler(socket);

            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        handler(socket);
                    } catch (Exception e) {
                        log.error("thread error: {}", e);
                    }
                }
            }).start();
        }

    }

    private static void handler(Socket socket) throws Exception{

        byte[] bytes = new byte[1024];

        log.info(" 准备 read .... ");

        // 接收客户端的数据，阻塞方法，没有数据可读时就阻塞
        int read = socket.getInputStream().read(bytes);

        if (read != -1) {
            log.info("接收到客户端的数据： {} ", new String(bytes, 0, read));
            socket.getOutputStream().write("helloClient".getBytes());
        }
//        socket.getOutputStream().flush();
    }
}
